package org.wk.core.web.tool;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.wk.core.web.covert.StringToDateInJson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


/**
 * 
 * @ClassName	: JSONUtils
 * @Package		：org.wk.core.web.tool
 * @Author df.w 
 * @Create Time	：2018年5月2日 上午10:14:51
 * @Description	:
 */
public class JSONUtils {
	/**
	 * @Title: beanCovertJSON 
	 * @Description: 对象转换为JSON 
	 * @return String 
	 * @throws
	 */
	public static <T> String beanCovertJSON(T t) {
		Gson gson = new GsonBuilder().create();
		return gson.toJson(t);
	}

	/**
	 * @Title: jsonCovertBean 
	 * @Description: JSON转化为对象类 
	 * @return T 
	 * @throws
	 */
	public static <T> T jsonCovertBean(String content, Class<T> clazz) {
		if (content == null || content.trim().length() == 0) {
			return null;
		}
		Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new StringToDateInJson()).create();
		return gson.fromJson(content, clazz);
	}

	/**
	 * @Title: jsonCovertList 
	 * @Description: 将JSON转化为LIST列表 @return
	 * List<T> @throws
	 */
	public static <T> List<T> jsonCovertList(String content, final Class<T> classOfT) {
		Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new StringToDateInJson()).create();
		ParameterizedType type = new ParameterizedType() {
			@Override
			public Type getRawType() {
				return List.class;
			}

			@Override
			public Type getOwnerType() {
				return null;
			}

			@Override
			public Type[] getActualTypeArguments() {
				return new Type[] { classOfT };
			}
		};
		return gson.fromJson(content, type);
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String, Object> parseMap(String json) {
		if (json != null) {
			json = json.trim();
			if (json.startsWith("{")) {
				return new GsonBuilder().create().fromJson(json, Map.class);
			}
		}
		throw new IllegalArgumentException("Cannot parse JSON");
	}

	@SuppressWarnings("unchecked")
	public static List<Object> parseList(String json) {
		if (json != null) {
			json = json.trim();
			if (json.startsWith("[")) {
				return new GsonBuilder().create().fromJson(json, List.class);
			}
		}
		throw new IllegalArgumentException("Cannot parse JSON");
	}

	public static JsonObject getJsonObject(String json) {
		// TODO Auto-generated method stub
		JsonParser jsonParser = new JsonParser();
		return jsonParser.parse(json).getAsJsonObject();
	}
}
